package com.leyou.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.PageResult;
import com.leyou.dao.SkuMapper;
import com.leyou.pojo.Sku;
import com.leyou.pojo.Spu;
import com.leyou.pojo.SpuDetail;
import com.leyou.pojo.SpuVo;
import com.leyou.service.SpuService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("spu")
public class SpuController {
    @Autowired
    private SpuService spuService;
    @Autowired
    private   AmqpTemplate amqpTemplate;
    @RequestMapping("page")
    public PageResult<SpuVo> page(
            @RequestParam(value = "key",required = false)String key,
            @RequestParam(value = "saleable",defaultValue = "2")Integer saleable,
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "rows",defaultValue = "5")Integer rows

    ){
        //查询所有数据
      PageResult<SpuVo>result= spuService.searchSpu(key,saleable,page,rows);
      return result;
    }


    @PostMapping("savaOrUpdateGoods")
    public void addMany(@RequestBody SpuVo spuVo ){
       this.spuService.save(spuVo);
       this.sendMessage("insert",spuVo.getId());
    }

    //通过spuid查询detail
    @RequestMapping("detail/{spu_id}")
    public SpuDetail detail(@PathVariable("spu_id") Integer spu_id){
        SpuDetail spuDetail=this.spuService.detail(spu_id);
        return spuDetail;
    }

   //通过spuid获取sku集合
    @RequestMapping("list")
    public List<Sku> list(@RequestParam("id") Integer id){
        List<Sku>  list=this.spuService.list(id);
        return list;
    }

    @PutMapping("savaOrUpdateGoods")
    public void updateMany(@RequestBody SpuVo spuVo){

        this.spuService.update(spuVo);
        this.sendMessage("update",spuVo.getId());
    }
    @RequestMapping("deleteById/{id}")
    public void deleteMany(@PathVariable("id") Integer id){
        this.spuService.deleteMany(id);
        this.sendMessage("delete",id);
    }
    @RequestMapping("upOrDown")
    public void upOrDown(
            @RequestParam("spuId")Integer spuId,
            @RequestParam("saleable")Integer saleable
    ){
        spuService.upOrDown(spuId,saleable);

    }



    //通过spu的id查询spu实体类
    @RequestMapping("findSpuBuId")
    public  Spu findSpuBuId(@RequestParam("spuid") Integer spuid){
        Spu spu= spuService.findSpuBuId(spuid);
        return spu;
    }
    //生产者

    public void  sendMessage(String type,Integer spuid){
        this.amqpTemplate.convertAndSend("item.exchanges","item."+type,spuid);
    }
}

